package com.adcc.foc.controller;

import com.adcc.foc.domain.ResultState;
import com.adcc.foc.domain.TreeNode;
import com.adcc.foc.domain.User;
import com.adcc.foc.page.Page;
import com.adcc.foc.service.OrganizationService;
import com.adcc.foc.service.UserService;
import com.adcc.foc.utils.CryptoUtil;
import com.adcc.foc.utils.Log;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by houxy on 2016/8/5.
 */
@Controller
public class MaintainUser extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private OrganizationService orgService;

    /**
     * 获取所有用户及部门信息
     *
     * @param req
     * @author houxy
     */
    @RequestMapping("toUserMaintain")
    public ModelAndView toUserMaintain(HttpServletRequest req, String compelltion, String deptId, String searchUserName) {
        //结果集
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //参数集
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //用户权限
        String isShowAll = (String) req.getSession().getAttribute("isShowAll");
        //用户账号
        String userName = (String) req.getSession().getAttribute("userName");
        try {
            //用户所属部门
            String orgId = userService.findUserByUserName(userName).getOrgid();
            //根据权限和所在部门获取可维护的部门
            List<TreeNode> orgs = orgService.getNodeList(orgId, isShowAll);
            //可维护部门的id
            List<String> orgIds = new ArrayList<String>();
            for (TreeNode t : orgs) {
                orgIds.add(t.getId());
            }
            paramMap.put("orgIds", orgIds);
            //姓名
            paramMap.put("compelltion", compelltion);
            //部门
            paramMap.put("deptId", deptId);
            //用户名
            paramMap.put("searchUserName", searchUserName);
            //权限
            paramMap.put("isShowAll", isShowAll);
            if ("-1".equals(isShowAll)) {
                new ModelAndView("error");
            }
            //获取总条数
            Long totalCount = userService.PageCounts(paramMap);
            //设置分页对象
            Page page = executePage(req, totalCount);
            paramMap.put("startIndex", page.getBeginIndex());
            paramMap.put("endIndex", page.getEndinIndex());
            List<User> users = userService.findByCondition(paramMap);

            //结果集
            resultMap.put("users", users);
            resultMap.put("compelltion", compelltion);
            resultMap.put("deptId", deptId);
            resultMap.put("orgs", orgs);
            resultMap.put("searchUserName", searchUserName);
            return new ModelAndView("userMaintain", resultMap);
        } catch (Exception e) {
            Log.error(ExceptionUtils.getFullStackTrace(e), MaintainUser.class);
        }
        return new ModelAndView("error");
    }

    /**
     * 删除用户信息
     *
     * @param userId 用户对应的id
     * @author houxy
     */
    @RequestMapping("deleteUser")
    @ResponseBody
    public Map<String, Object> deleteUser(String userId) {
        Map<String, Object> map = null;
        try {
            map = userService.deleteUser(userId);
            map.put("status", ResultState.SUCCESS);
        } catch (Exception e) {
            Log.error(ExceptionUtils.getFullStackTrace(e), MaintainUser.class);
            map.clear();
            map.put("status", ResultState.ERROR);
        }
        return map;
    }

    /**
     * 根据登录用户的权限获取可以维护的部门和所有权限
     *
     * @author houxy
     */
    @RequestMapping("getDeptAndRoles")
    @ResponseBody
    public Map<String, Object> getAlldept(HttpServletRequest req) {
        Map<String, Object> map = null;
        try {
            String isShowAll = (String) req.getSession().getAttribute("isShowAll");
            String userName = (String) req.getSession().getAttribute("userName");
            if ("-1".equals(isShowAll)) {
                throw new RuntimeException("你无此权限!");
            }
            User user = userService.findUserByUserName(userName);
            map = userService.findDeptAndRoles(user.getOrgid(), isShowAll);
            map.put("status",ResultState.SUCCESS);
        } catch (Exception e) {
            Log.error(ExceptionUtils.getFullStackTrace(e), MaintainUser.class);
            map.clear();
            map.put("status",ResultState.ERROR);
        }
        return map;
    }

    /**
     * 添加用户
     *
     * @param username 用户名
     * @param password 密码(明文)
     * @param orgid    部门对应id
     * @author houxy
     */
    @RequestMapping("saveUser")
    @ResponseBody
    public Map<String, Object> saveUser(String username, String password, String orgid, String compelltion, String roleId,String key) {
        Map<String, Object> map = null;
        try {
            username = CryptoUtil.decryptString(username,key);
            password = CryptoUtil.decryptString(password,key);
            map = userService.saveUser(username, password, orgid, compelltion, roleId);
            map.put("status",ResultState.SUCCESS);
        } catch (Exception e) {
            Log.error(ExceptionUtils.getFullStackTrace(e), MaintainUser.class);
            map.clear();
            map.put("status",ResultState.ERROR);
        }
        return map;
    }

    /**
     * 获取用户的信息
     *
     * @param userId
     * @return
     */
    @RequestMapping("getUserInfo")
    @ResponseBody
    public Map<String, Object> getUserInfo(String userId, HttpServletRequest req) {
        Map<String, Object> map = null;
        try {
            String isShowAll = (String) req.getSession().getAttribute("isShowAll");
            String userName = (String) req.getSession().getAttribute("userName");
            if ("-1".equals(isShowAll)) {
                throw new RuntimeException("你无此权限!");
            }
            User user = userService.findUserByUserName(userName);
            map = userService.findUserInfoAndDeptAndRoles(user.getOrgid(), isShowAll, userId);
            map.put("status",ResultState.SUCCESS);
        } catch (Exception e) {
            Log.error(ExceptionUtils.getFullStackTrace(e), MaintainUser.class);
            map.clear();
            map.put("status",ResultState.ERROR);
        }
        return map;
    }

    /**
     * 修改用户信息
     *
     * @param userId 用户id
     * @param orgid  转入的部门id
     * @author houxy
     */
    @RequestMapping("alterUser")
    @ResponseBody
    public Map<String, Object> alterUser(String userId, String orgid, String roleId, String compelltion) {
        Map<String, Object> map = null;
        try {
            map = userService.alterUser(userId, orgid, roleId, compelltion);
            map.put("status",ResultState.SUCCESS);
        } catch (Exception e) {
            Log.error(ExceptionUtils.getFullStackTrace(e), MaintainUser.class);
            map.clear();
            map.put("status",ResultState.ERROR);
        }
        return map;
    }

    /**
     * 检查当前用户是否有维护用户和组织的权限
     *
     * @return
     */
    @RequestMapping("checkAuthority")
    public String checkAuthority(String token, HttpSession session, RedirectAttributes redirectAttributes) {
        try {
            //如果令牌为空，或者令牌不是以“Bearer ”开头的
            if (token == null || !token.startsWith("Bearer ")) {
                return "error";
            }
            String isShowAll = (String) session.getAttribute("isShowAll");
            boolean isPass;
            switch (isShowAll) {
                case "0":
                case "1":
                case "2":
                    isPass = true;
                    break;
                default:
                    isPass = false;
                    break;
            }
            if (isPass) {
                return "redirect:/toUserMaintain";
            } else {
                redirectAttributes.addAttribute("message", "error");
                return "redirect:/desktop";
            }
        } catch (Exception e) {
            Log.error(ExceptionUtils.getFullStackTrace(e), MaintainUser.class);
        }
        return "error";
    }

    /**
     * 重置选中用户登录密码（123456）
     *
     * @param userId
     * @return
     */
    @RequestMapping("forceResetPassword")
    @ResponseBody
    public Map<String, Object> forceResetPassword(String userId) {
        Map<String, Object> map = new HashMap<>();
        try {
            userService.forceResetPassword(userId);
            map.put("status",ResultState.SUCCESS);
        } catch (Exception e) {
            Log.error(ExceptionUtils.getFullStackTrace(e), MaintainUser.class);
            map.put("status",ResultState.ERROR);
        }
        return map;
    }
}
